package com.cskaoyan.jdbc.dbutils;

import com.cskaoyan.jdbc.datasource.druid.DruidUtils;
import com.cskaoyan.jdbc.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;

import javax.management.Query;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 创建日期: 2022/05/16 10:20
 *
 * @author ciggar
 */
public class DBUtilsDemo {


    public static void main(String[] args) throws SQLException {

//        queryRunnerDemoWithConnection();

//        queryRunnerDemoWithOutConnection();

        queryRunnerWithConnectionQuery();

    }


    // 传入Connection 案例
    public static void queryRunnerDemoWithConnection() throws SQLException {

        // 构造无参的queryRunner
        QueryRunner queryRunner = new QueryRunner();

        Connection connection = DruidUtils.getConnection();

        // update方法可以执行增删改的方法
//        int affectedRows = queryRunner.update(connection, "insert into stu values (11,'张居正',30,'六班')");

        int affectedRows = queryRunner.update(connection,"insert into stu values (?,?,?,?)",12,"海瑞",40,"七班");

        System.out.println(affectedRows);

        // 关闭资源
        JDBCUtils.close(connection,null,null);

    }



    // 不传入Connection 案例
    public static void queryRunnerDemoWithOutConnection() throws SQLException {

        // 获取数据库连接池
        DataSource dataSource = DruidUtils.getDataSource();

        // 构造QueryRunner
        QueryRunner queryRunner = new QueryRunner(dataSource);

        int affectedRows = queryRunner.update("update stu set name = ? where id = ?", "嘉靖皇帝", 4);

        System.out.println(affectedRows);
    }


    // 执行查询方法 传入Connection对象
    public static void queryRunnerWithConnectionQuery() throws SQLException {

        // 1. 创建一个QueryRunner
        QueryRunner queryRunner = new QueryRunner();

        // 2. 执行SQL语句
        Object object = queryRunner.query(DruidUtils.getConnection(), "select * from stu where id = ?", new MyResultSetHandler(), 4);


        // 3. 打印对象
        System.out.println(object);

    }








}
